//
//  YCYTXIMManager.m
//  DemoYTX
//
//  Created by 唐可雄 on 16/7/12.
//  Copyright © 2016年 swustyc. All rights reserved.
//

#import "YCYTXIMManager.h"

#import "YCYTXIMDBManager.h"

#define kYTX_APPKEY     @"8a48b5515493a1b70154c16c13f32cc0"
#define kYTX_APPTOKEN   @"f749c428fdf806edd0d20f186b45fed7"

NSString * const kNotification_YTXConnectDidChange = @"kNotification_YTXConnectDidChange";
NSString * const kNotification_YTXNeedSetUserInfo  = @"kNotification_YTXNeedSetUserInfo";

static YCYTXIMManager *manager = nil;

@interface YCYTXIMManager ()

@property (nonatomic, strong) YCYTXIMDBManager *dbManager;

@end

@implementation YCYTXIMManager

+ (instancetype)sharedInstance {
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        manager = [[YCYTXIMManager alloc] init];
    });
    
    return manager;
}

#pragma mark - Setter and Getter

- (void)setUserID:(NSString *)userID {
    _userID = [userID copy];
    
    self.dbManager = [YCYTXIMDBManager instanceWithUserID:_userID];
}

#pragma mark - Public Methods

- (void)loginNormalWithUserID:(NSString *)userID block:(void (^)(ECError *))block {
    ECLoginInfo * loginInfo = [[ECLoginInfo alloc] init];
    loginInfo.username = userID;
    loginInfo.appKey = kYTX_APPKEY;
    loginInfo.appToken = kYTX_APPTOKEN;
    loginInfo.authType = LoginAuthType_NormalAuth;
    loginInfo.mode = LoginMode_InputPassword;
    [[ECDevice sharedInstance] login:loginInfo completion:^(ECError *error){
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotification_YTXConnectDidChange object:error];
        
        if (error.errorCode == ECErrorType_NoError) {
            self.userID = userID;
        }
        
        block(error);
    }];
}

#pragma mark - ECDeviceDelegate

- (void)onConnectState:(ECConnectState)state failed:(ECError *)error {
    
}

- (void)onReceiveMessage:(ECMessage *)message {
    
}

- (void)onServicePersonVersion:(unsigned long long)version {
    if ([DemoGlobalClass sharedInstance].dataVersion==0 && version==0) {
        [DemoGlobalClass sharedInstance].isNeedSetData = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_needInputName object:nil];
    } else if (version>[DemoGlobalClass sharedInstance].dataVersion) {
        [[ECDevice sharedInstance] getPersonInfo:^(ECError *error, ECPersonInfo *person) {
            if (error.errorCode == ECErrorType_NoError) {
                [DemoGlobalClass sharedInstance].dataVersion = person.version;
                [DemoGlobalClass sharedInstance].birth = person.birth;
                [DemoGlobalClass sharedInstance].nickName = person.nickName;
                [DemoGlobalClass sharedInstance].sex = person.sex;
                [DemoGlobalClass sharedInstance].sign = person.sign;
            }
        }];
    }
}

@end
